package com.maserb.monitor.service.schoolForum.impl;

import com.maserb.monitor.entity.schoolForum.PostEntity;
import com.maserb.monitor.repository.schoolForum.PostRepository;
import com.maserb.monitor.service.base.impl.JpaSpecificationServiceImpl;
import com.maserb.monitor.service.schoolForum.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.StringUtils;

import javax.persistence.criteria.*;
import java.util.ArrayList;

@Service
public class PostServiceImpl extends JpaSpecificationServiceImpl<PostRepository,
        PostRepository, PostEntity, String>
        implements PostService {

    @Autowired
    private PostRepository postRepository;

    private Specification<PostEntity> getSpecification(String keyword,String orgId) {
        return new Specification<PostEntity>()  {
            @Override
            public Predicate toPredicate(Root<PostEntity> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                Path<String> pathTitle = root.get("title");
                Path<String> pathSchoolId = root.get("schoolId");
                ArrayList<Predicate> list = new ArrayList<Predicate>();
                if (!StringUtils.isEmptyOrWhitespace(keyword)) {
                    list.add(criteriaBuilder.and(criteriaBuilder.like(pathTitle, "%" + keyword + "%")));
                }
                if (!StringUtils.isEmptyOrWhitespace(orgId)) {
                    list.add(criteriaBuilder.and(criteriaBuilder.equal(pathSchoolId, orgId)));
                }

                return criteriaBuilder.and(list.toArray(new Predicate[list.size()]));
            }
        };
    }

    @Override
    public Page<PostEntity> findAll(Pageable pageable, String keyword,String orgId) {
        return this.findAll(getSpecification(keyword,orgId), pageable);
    }

    @Override
    public void doTop(String id) {
        PostEntity entity = this.findOne(id);
        entity.setIsTop("1");
        this.save(entity);
    }

    @Override
    public void cancelTop(String id) {
        PostEntity entity = this.findOne(id);
        entity.setIsTop("0");
        this.save(entity);
    }
}